<template>
  <div>
    <div id="Button_list">
      <div :class="{'open':button_list_on}" @click="button_list_switch"><img src="~@/assets/img/u1396.svg" alt="" style="position: absolute"></div>
      <ul :class="{'open':!button_list_on}">
        <li @click="button_list_switch"><img src="~@/assets/img/u1398.svg" alt=""></li>
        <li @click="orderListOpen">产品列表</li>
        <li @click="SavesProduct" v-if="!!template_sn" v-show="is_save_module != '3'">放入模板</li>
        <li @click="save_productInfo" v-if="!!template_sn">保存产品</li>
        <li><a @click="SavesOrder">重建订单</a></li>
        <li><a @click="back_top">返回顶部</a></li>
      </ul>
    </div>
    <div style="padding: 0 20px;height:48px;position: fixed;bottom: 20px;right: 40px;border-radius: 1000px;background-color:#f9d532;" v-show="is_save_module=='3'">
      <p style="line-height: 48px;text-align: center;font-size: 14px;color: #000000;font-weight: bolder;cursor: pointer;" @click="SavesProduct" v-if="!!template_sn">保存为铭朗云模板</p>
    </div>
    <div v-show="backtop==true" style="width: 50px;height: 50px;border-radius: 500px;background-color: #2D2D2D;position:fixed;bottom: 80px;right: 40px;text-align: center;cursor: pointer;" @click="back_top">
      <img src="../../assets/img/mlcc_top.png" width="40" height="40" style="margin-top: 5px;">
    </div>

    <div class="zhezhao" :class="order_list_open" @click="toggle"></div>
    <div style="position: fixed;top: 0;bottom: 0;left: 0;right: 0;background: rgb(0,0,0,0.5);z-index: 2;" v-show="shadeShow" @click="colse"></div>
    <div id="CreateOrder" :class="order_list_open" v-loading="loading">
      <div class="title">
        <span>已保存产品列表</span>
        <a><span @click="colse" style="float:right;margin-right: 10px;">关闭</span></a>
        <a><span @click="shuaxin" style="float:right;margin-right: 10px;">刷新</span></a>
      </div>
      <div class="list" v-for="(x,index) in productData" :key="index">
        <div class="li" style="padding-top: 16px">
          <div style="float: left">
            <el-image
                style="width: 100%;height: 100%"
                :src="x.productImg"
                fit="cover"></el-image>
          </div>
          <ul style="float: left">
            <li><label>产品</label><span style="font-size: 12px">{{x.productName}}</span></li>
            <li><label>品类</label><span style="font-size: 12px">{{x.leibieName}}</span></li>
            <li><label>面料</label><span style="font-size: 12px">{{x.fabricName}}</span></li>
            <!--                    <li style="padding-right: 5px"><label>折前价格</label>{{x.zheqianPrice}}元</li>-->
            <!--                    <li><label>折后价格</label>{{x.zhehouPrice}}元</li>-->
          </ul>
        </div>
        <div class="button">
          <div class="edit" @click="Edit(x.id)">编辑</div>
          <div class="delete" @click="Delete(x,index)">删除</div>
          <div class="delete" @click="copy_product(x.id)">复制产品</div>
        </div>
      </div>
      <!--            <el-pagination v-if="productData.length" background layout="prev, pager, next" :total="pageTotal" :current-page.sync="pageNo" :page-size="pageSize" @current-change="pageChangePage" style="padding: 20px 0;text-align: center;"></el-pagination>-->
      <div>
        <el-button class="create" type="warning" @click="Create">新建产品</el-button>
      </div>
    </div>
    <div class="zhezhao" :class="save_product_open" @click="toggle2"></div>
    <div :class="save_product_open" class="buy_wrap">
      <div class="buy">
        <div class="title">保存模板</div>
        <el-form :model="rule2" :rules="rules2" ref="forms" label-width="90px">
          <el-form-item label="名称" prop="templateName">
            <el-input v-model="rule2.templateName" placeholder="请填写订单/模板名称" clearable></el-input>
          </el-form-item>
        </el-form>
        <div class="button">
          <button class="delete" @click="toggle2">取消</button>
          <button class="edit" @click="Saves">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Qs from "qs";
import { deleteAction, postAction, getAction } from '@/api/manage'
export default {
  name: 'Orderlist',
  data() {
    return{
      loading:false,
      backtop:false,
      is_save_module:0,
      button_list_on: true,//底部按钮组件
      order_list_open: 'close',//产品列表收展开关
      productData: [],//产品列表数据
      template_sn: this.$store.state.OrderUser.Order_user_Info_temp.templateSn,//模板编号
      order_sn:this.$store.state.OrderUser.Order_user_Info_temp.orderSn,//订单编号
      save_product_open: 'close',
      rule2: {
        templateName: ''
      },
      rules2: {
        templateName: [{ required: true, message: '请填写' }]
      },
      // 分页
      pageTotal: 0, // 总条数
      pageNo: 1,  // 当前页码
      pageSize: 1000,  // 页条数
      // 遮罩
      shadeShow: false
    }
  },
  created() {
    this.show_userinfo();
  },
  //第一步
  mounted() {
    //获取当前的页面滚动事件，然后执行 this.showheader事件
    window.addEventListener('scroll', this.showheader);
    // this.show_userinfo();
  },
  destroyed() {
    window.removeEventListener('scroll', this.showheader);
  },
  methods:{
    show_userinfo() {
      let autohor_token = localStorage.getItem("token");
      let params = {token: autohor_token};
      postAction(domain.publicUrl + "/user/interface/query_userInfoBytoken", Qs.stringify(params)).then(res => {
        let result = res.data;
        if (result.code == 0) {
          this.is_save_module=result.data.identity;
        } else {
          this.$message.warning("您的登录已失效，请重新登录")
          this.$router.replace({
            path:'/login',
            name:'login'
          })
          localStorage.removeItem("token");
          window.history.go(0);
        }
      })
    },
    // 统一分页触发事件
    pageChangePage(index) {
      this.pageNo = index;
      // 触发事件方法函数
      this.orderListOpen()
    },
    //第二步
    showheader: function() {
      //当前屏幕等于多少执行的事件
      var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
      this.scrollTop = scrollTop
      console.log(scrollTop)
      if (scrollTop > 541) {
        //当屏幕大于541的时候，就显示，小于则不显示
        this.show = true;
        this.backtop = true;
      } else {
        this.show = false;
        this.backtop = false;
      }
    },
    back_top(){
      //返回头部的动画
      const that = this
      let timer = setInterval(() => {
        let ispeed = Math.floor(-that.scrollTop / 7)
        document.documentElement.scrollTop = document.body.scrollTop = that.scrollTop + ispeed
        if (that.scrollTop === 0) {
          clearInterval(timer)
        }
      }, 10)
    },
    // // 为了计算距离顶部的高度，当高度大于60显示回顶部图标，小于60则隐藏
    // scrollToTop () {
    //     const that = this
    //     let scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop
    //     that.scrollTop = scrollTop
    //     if (that.scrollTop > 0) {
    //         that.btnFlag = true
    //     } else {
    //         that.btnFlag = false
    //     }
    // },
    save_productInfo(){//保存产品
      this.$store.commit('postOrder_user_product_update',0);
      this.$message.success("保存产品成功")
      // this.$store.commit('saveOrderUserTemplate');
    },
    copy_product(product_id){//复制产品
      this.loading = true;
      let params = new FormData();
      params.append('token',localStorage.getItem("token"));
      params.append('id',product_id);
      this.$http.post('logic/interface/copy_singleorder_products',params).then((res) => {
        if(res.data.code==0){
          this.$message.success("复制产品成功");
          //执行刷新
          this.shuaxin();
          this.loading = false;
        }else {
          this.$message.error(res.data.msg);
          this.loading = false;
        }
      });
    },
    button_list_switch() {
      this.button_list_on = !this.button_list_on;
    },
    shuaxin(){//刷新产品列表
      let ordersn = this.$store.state.OrderUser.Order_user_InfoData.orderSn;
      if(ordersn!=null && ordersn!=''){
        let params = new FormData();
        params.append('token',localStorage.getItem("token"));
        params.append('orderSn',ordersn);
        this.$http.post('/fabricAndOther/getDingleOrderDetail',params).then((res) => {
          // alert(res.data.data)
          this.$store.state.OrderUser.Order_user_InfoData = res.data.data;
          this.$store.state.OrderUser.Order_user_InfoData.token = localStorage.getItem("token");
          this.$store.state.OrderUser.Order_user_Info_temp.templateSn = res.data.data.productInfoList[0].templateSn;
          // //产品信息复位
          // this.$store.dispatch('setProductInfo',0);
          // this.$router.push({path:'/order_user/index'});
        });
      }

      let p1 = new FormData();
      p1.append('token',localStorage.getItem("token"));
      p1.append('orderSn',this.$store.state.OrderUser.Order_user_InfoData.orderSn);
      // 接口加按分页返回数据
      p1.append('pageNo',this.pageNo);
      p1.append('pageSize',this.pageSize);
      this.$http.post('logic/interface/query_AllproductsByordersn',p1).then(result => {
        this.productData = result.data.data;
        this.pageTotal = result.data.data.total; // 接口返回数据中没有，需要加上赋值
        // alert(result.data.data)
        // if(result.data.data.length > 1 || result.data.data[0].leibieName != '暂无') {
        //     this.productData = result.data.data;
        // }
      });
      this.order_list_open = 'open';
    },
    // 产品列表
    orderListOpen() {
      let ordersn = this.$store.state.OrderUser.Order_user_InfoData.orderSn;
      if(ordersn!=null && ordersn!=''){
        let params = new FormData();
        params.append('token',localStorage.getItem("token"));
        params.append('orderSn',ordersn);
        this.$http.post('/fabricAndOther/getDingleOrderDetail',params).then((res) => {
          // alert(res.data.data)
          this.$store.state.OrderUser.Order_user_InfoData = res.data.data;
          this.$store.state.OrderUser.Order_user_InfoData.token = localStorage.getItem("token");
          this.$store.state.OrderUser.Order_user_Info_temp.templateSn = res.data.data.productInfoList[0].templateSn;
          // //产品信息复位
          // this.$store.dispatch('setProductInfo',0);
          // this.$router.push({path:'/order_user/index'});
        });
      }

      let p1 = new FormData();
      p1.append('token',localStorage.getItem("token"));
      p1.append('orderSn',this.$store.state.OrderUser.Order_user_InfoData.orderSn);
      // 接口加按分页返回数据
      p1.append('pageNo',this.pageNo);
      p1.append('pageSize',this.pageSize);
      this.$http.post('logic/interface/query_AllproductsByordersn',p1).then(result => {
        if(result.data.data.length > 0 || result.data.data[0].leibieName != '暂无') {
          this.productData = result.data.data;
          this.pageTotal = result.data.data.total; // 接口返回数据中没有，需要加上赋值
        }
      });
      this.shadeShow = true
      this.order_list_open = 'open';
    },
    colse(){
      this.shadeShow = false
      this.order_list_open = 'close';
    },
    toggle() {
      this.order_list_open = this.order_list_open == 'open' ? 'close' : 'open';
    },
    toggle2() {
      this.save_product_open = this.save_product_open == 'open' ? 'close' : 'open';
    },
    SavesProduct() {
      this.save_product_open = 'open';
    },
    Saves() {
      this.$refs['forms'].validate(valid => {
        if(valid) {
          this.$store.commit('saveOrderUserTemplate',this.rule2.templateName);
          this.$message.success("保存成功");
          // this.$message({
          //     message:'保存成功',
          //     type:'success',
          //     duration: 1500
          // });
          this.save_product_open = 'close';
        }
      });
    },
    SavesOrder(){//重建订单再保存当前订单
      this.$store.commit('postOrder_user_product_update',0);
      this.$router.replace({
        path:'/',
        name:'home'
      })
      // this.$router.push('./view/'+this.$store.state.OrderUser.Order_user_InfoData.orderSn);
      // let p1 = new FormData();
      // p1.append('token',localStorage.getItem("token"));
      // p1.append('orderSn',this.$store.state.OrderUser.Order_user_Info_temp.orderSn);
      // this.$http.post('logic/interface/update_single_order',p1).then(result => {
      //     this.$router.replace({
      //         path:'/',
      //         name:'home'
      //     })
      // });
    },
    Edit(productId) {
      this.show=false;
      // let nolength = true;
      // alert(this.$store.state.OrderUser.Order_user_InfoData.productInfoList[0].id+"==="+productId+"==大小="+this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length)
      if(this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length>0){
        // alert("不谈啊="+productId)
        for(let i=0;i<this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length;i++) {
          if(this.$store.state.OrderUser.Order_user_InfoData.productInfoList[i].id==productId){
            // alert("===3333==="+i)
            this.shadeShow = false
            this.order_list_open = 'close';
            this.$store.dispatch('setProductInfo', i);
            break
          }else {
            this.shadeShow = false
            // alert("===222==="+i)
            this.order_list_open = 'close';
            this.$store.dispatch('setProductInfo', i);
          }
        }
        // nolength = false;
        // alert("弹了这个"+productId)
        // this.order_list_open = 'close';
        // this.$store.dispatch('setProductInfo', 1);

        // this.$store.dispatch('setProductInfo',i)
        // if(this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length==1){
        //     //订单详情里还没有第二个产品时
        //     // this.$store.commit('addProduct',productId);
        //     this.$store.dispatch('setProductInfo', this.$store.state.OrderUser.Order_user_InfoData.productInfoList[0].id)
        //     alert("谈了这个吗="+productId)
        // }else {
        //     // for(let i=0;i<this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length;i++) {
        //     //     this.$store.dispatch('setProductInfo', i)
        //     // }
        //     // this.$store.commit('addProduct',productId);
        //     nolength = false;
        //     this.$store.dispatch('setProductInfo', productId)
        //     this.order_list_open = 'close';
        //     alert("弹了这个"+this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length)
        // }
      }else {
        this.$message.error("该订单暂无产品")
      }

      // let nolength = true;
      // for(let i=0;i<this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length;i++) {
      //     if(this.$store.state.OrderUser.Order_user_InfoData.productInfoList[i].id == productId) {
      //         if(nolength) {
      //             //订单详情里还没有第二个产品时
      //             this.$store.commit('addProduct',productId);
      //         }
      //         this.order_list_open = 'close';
      //         alert("jlamlklk");
      //     }else {
      //         nolength = false;
      //         this.$store.dispatch('setProductInfo',i)
      //         alert("jlamlklk=====");
      //     }
      // }
      // if(nolength) {
      //     //订单详情里还没有第二个产品时
      //     this.$store.commit('addProduct',productId);
      // }
      // this.order_list_open = 'close';
    },
    Delete(item,index) {
      //单删
      if(this.$store.state.OrderUser.Order_user_InfoData.productInfoList.length <= 1 && this.$store.state.OrderUser.Order_user_InfoData.productInfoList[0].id == item.id) {
        // this.$message({
        //     message:'请至少保留一个已保存的产品',
        //     type:'error',
        //     duration: 1500
        // });
        this.$message.error("请至少保留一个已保存的产品");
        return false;
      }
      if(confirm('确认要删除吗？')) {
        let p1 = new FormData();
        p1.append('token',localStorage.getItem("token"));
        p1.append('order_sn',item.id);
        p1.append('type',5);
        this.$http.post('logic/interface/deleteBytype',p1).then((res) => {
          this.productData.splice(index, 1);

          //删除后要处理一下，如果当前面板状态定位为即删除产品，那产品删除后，面板数据就不能是已经删除过的产品信息了
          //处理一下复位到最近一个产品上。如果删除了已经保存的产品，停留了一个订单内还未保存的产品，会不会出问题？
          this.$store.dispatch('setProductInfo',0);
        });
      }
    },
    Create() {
      if(this.$store.state.OrderUser.Order_user_Info_temp.bodySizeIds != null && this.$store.state.OrderUser.Order_user_Info_temp.bodySizeIds != ''){
        this.$store.state.OrderUser.Order_user_Info_temp.bodySizeIds='';
      }
      let p1 = new FormData();
      p1.append('token',localStorage.getItem("token"));
      p1.append('orderSn',this.$store.state.OrderUser.Order_user_Info_temp.orderSn);
      p1.append('templateSn',this.$store.state.OrderUser.Order_user_Info_temp.templateSn);
      this.$http.post('logic/interface/insert_products',p1).then(result => {
        this.orderListOpen();
        this.$store.dispatch('addProduct',result.data.productId);
        this.shadeShow = false
        this.order_list_open = 'close';
      });
    }
  },
  watch: {
    //使用watch监听，判断弹出框是显示状态或隐藏状态
    shadeShow: {
      //布尔类型变量,是否展示弹框
      handler(val) {
        //true:显示弹出框，false：隐藏弹出框
        if (val) {
          document.querySelector('body').setAttribute('style', 'overflow:hidden;')
        } else {
          document.body.removeAttribute('style')
        }
      }
    }
  },
}
</script>

<style scoped lang="scss">
#Button_list{position: fixed; height: 70px; font-size: 14px;bottom: 20px;}
#Button_list div,#Button_list ul{position: fixed; left:-400px;}
#Button_list div.open,#Button_list ul.open{left:40px;background-color: #fff;margin-right: 80px;border-radius: 300px;box-shadow: 0px 0px 6px 5px #e3e3e3;}
#Button_list div{cursor: pointer;transition: all .7s ease-out;}
#Button_list ul{display: flex; flex-flow: wrap;align-items: center; text-align: center;cursor: pointer;
  transition: all .7s ease-out;left: -500px;
}
#Button_list ul li{ width: 80px;}
#Button_list ul li:first-child{text-align: left; width: 70px;}


#CreateOrder.open{transition: all .7s ease-out;}
#CreateOrder.close{right: -580px; visibility: hidden;}
#CreateOrder{background: #ffffff; z-index: 999; min-width: 300px; position: fixed; top:0;right: 0px; overflow-y: scroll; padding: 20px 0px 0 20px; height: 100%;
  padding-bottom: 20px}

#CreateOrder .title{ margin: 10px 0 20px 0px; border-left: 5px solid #000000; padding-left: 15px;font-size: 16px;}
.list{ margin-bottom: 20px;}
.li{display: flex;flex-flow: wrap; width: 460px;}
.li div{width: 120px; border: 1px solid #D8D8D8; border-radius: 4px; margin-right: 10px;}
.li div img{ width: 98%; display: block; margin: 0 auto;}
.li ul li{ height: 34px; line-height: 34px;}
.li ul li label{width: 80px; display: inline-flex; background: #FAFAFA; padding-left: 20px; margin-right: 20px;}
.button{ display: flex; justify-content: flex-end; text-align: center; margin-top: 10px;}
.button div{ width: 100px; height: 40px; line-height: 40px; border-radius: 5px; margin-right: 20px; cursor: pointer;}
.button .edit{ background: #000000; color: #FFFFFF;}
.button .delete{background: #EAEAEA;}
.create{ width: 50%;margin: 0 auto 0 24%;}


.buy_wrap{position: absolute; height: 100%;}
.buy_wrap.open .buy{transition: all .7s ease-out;}
.buy_wrap.close .buy{top: 100px; visibility: hidden;}
.buy_wrap .buy{background: #ffffff; z-index: 999; position: fixed;height: 200px; top:50%;left: 50%; padding: 20px 30px;
  border-radius: 5px; width: 450px;margin-top: -100px;margin-left: -225px;box-shadow: 1px 1px 20px 1px #e2e2e2}
.buy_wrap .buy .el-input{width: 240px;}
.buy_wrap .buy .title{ margin: 0px 0 20px 0px; border-left: 5px solid #000000; padding-left: 15px;font-size: 16px;}
.buy_wrap .buy .button{float: right;}
.buy_wrap .buy button{ border:none; width: 100px; height: 40px; line-height: 40px; border-radius: 5px; margin-left: 20px; cursor: pointer;}
.buy_wrap .buy .edit{ background: #000000; color: #FFFFFF;}
.buy_wrap .buy .delete{background: #EAEAEA;}
</style>
